import {AutoPagesOptions, AutoPagesPluginInternalOptions, AutoPagesPluginOptions} from "../types";
import {loadConfig} from "unconfig";
import {DefaultAutoPagesOptions, DefaultAutoPagesPluginOptions} from "../constant";
import {mergeObject} from "../utils/merge";
import path from "path";
import process from "node:process";
import {Logger, normalizePath} from 'vite';

export class ConfigLoader {
    /**
     * 插件配置
     */
    private pluginConfig: AutoPagesPluginInternalOptions = DefaultAutoPagesPluginOptions;
    /**
     * 页面配置
     */
    private pagesConfig: AutoPagesOptions = DefaultAutoPagesOptions;

    /**
     * 配置文件路径列表（实际加载的文件）
     */
    private configFilePaths: string[] = [];

    /**
     * Logger 实例
     */
    private logger: Logger;

    /**
     * 构造函数
     * @param userPluginConfig 用户插件配置
     * @param logger 日志记录器
     */
    constructor(userPluginConfig: AutoPagesPluginOptions, logger: Logger) {
        this.logger = logger;
        this.loadPluginConfig(userPluginConfig);
    }

    /**
     * 加载页面配置
     * @returns 配置对象
     */
    public async loadPagesConfig(): Promise<AutoPagesOptions> {
        try {
            const {config, sources} = await loadConfig<AutoPagesOptions>({
                sources: [
                    // 支持多种配置文件格式
                    {
                        files: 'pages.config',
                        extensions: ['ts', 'js', 'json']
                    }
                ],
                cwd: this.pluginConfig.root
            });

            // 记录实际加载的配置文件路径，并标准化路径格式
            this.configFilePaths = sources.filter(Boolean).map(configPath => normalizePath(configPath));

            if (!config) {
                this.logger.warn('未找到页面配置文件，使用默认配置');
                this.pagesConfig = DefaultAutoPagesOptions;
            } else {
                this.pagesConfig = mergeObject(DefaultAutoPagesOptions, config);
            }
        } catch (error) {
            this.logger.error(`页面配置加载失败: ${error}`);
            this.pagesConfig = DefaultAutoPagesOptions;
            this.configFilePaths = [];
        }
        return this.pagesConfig;
    }

    /**
     * 处理插件配置
     * @param userPluginConfig 用户插件配置
     */
    public loadPluginConfig(userPluginConfig: AutoPagesPluginOptions) {
        this.pluginConfig = mergeObject(DefaultAutoPagesPluginOptions, userPluginConfig || {}) as AutoPagesPluginInternalOptions;
        this.pluginConfig.root = userPluginConfig && userPluginConfig.root ? path.resolve(userPluginConfig.root) : process.cwd();
        this.pluginConfig.pagesJsonPath = path.resolve(this.pluginConfig.root, this.pluginConfig.outputPath);
        return this.pluginConfig;
    }

    get pages(): AutoPagesOptions {
        return this.pagesConfig;
    }

    get plugin(): AutoPagesPluginInternalOptions {
        return this.pluginConfig;
    }

    /**
     * 获取配置文件路径列表
     * @returns 配置文件路径数组
     */
    public getConfigPaths(): string[] {
        // 返回实际加载的配置文件路径
        return this.configFilePaths;
    }
}
